using System;
using System.Threading;

class App {
   static Object l = new Object();
   static Mutex m = new Mutex();
   static Boolean UseMutex = true;

   static void EnterLock() {
      if (UseMutex) m.WaitOne();
      else Monitor.Enter(l);
   }
   
   static void ExitLock() {
      if (UseMutex) m.ReleaseMutex();
      else Monitor.Exit(l);
   }

   static void Main(string[] args) {
      EnterLock();
      ExitLock();
      Console.WriteLine("Press <enter> to exit app.");
      WaitCallback wc = new WaitCallback(M);
      for (Int32 times = 0; times < 5; times++) {
         EnterLock();
         Int32 x = 0;
         for (; x < 4; x++) {
            ThreadPool.QueueUserWorkItem(wc, x);
            Thread.Sleep(500);
         }
         ExitLock();
         ThreadPool.QueueUserWorkItem(wc, x);
         Console.ReadLine();
      }
   }

   static void M(Object o) {
      Console.WriteLine("EnterLock: " + o);
      EnterLock();
      Console.WriteLine(o + " ");
      ExitLock();
   }
}
